package com.qifan.alb2b.action.common;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.qifan.alb2b.exception.BusinessException;

/**
 * 通用文件上传
 * @author hc24
 *
 */
@Controller
public class UploadController{
	private final static Log logger = LogFactory.getLog(UploadController.class);
	
	@RequestMapping("/common/upload.con")
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fieldName=request.getParameter("fieldName");
		// 判断request是不是multiparty请求；
		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> map=multipart.getFileMap();
			Iterator<String> it=map.keySet().iterator();
			while(it.hasNext()){
				MultipartFile file = map.get(it.next());
				if (file == null || file.isEmpty()) {
					throw new BusinessException("请选择上传文件");
				}
				String filename = file.getOriginalFilename();
				logger.info("Upload file name:" + filename);
				// 获得文件扩展名
				String ext = "";
				int pos;
				if ((pos = filename.lastIndexOf(".")) != -1) {
					ext = filename.substring(pos).trim();
				}
	
				InputStream input = null;
				OutputStream output = null;
				String dirStr=request.getSession().getServletContext()
				.getRealPath("/upload")+"/"+ext;
				File dir=new File(dirStr);
				if(!dir.exists())
					dir.mkdirs();
				// 确定服务器端写入文件的文件名
				String strName= System.currentTimeMillis() + ext;
				String uploadfile = dirStr+"/"+strName; 
				
				try{
					//获得上传文件的输入流
					input=file.getInputStream();
					//写入服务器的本地文件
					output=new BufferedOutputStream(new FileOutputStream(uploadfile));
					byte[] buffer=new byte[1024];
					int n;
					while((n=input.read(buffer))!=-1)
						output.write(buffer,0,n);
					//告诉浏览器文件上传成功
					Map<String, Object> model=new ModelMap();
					model.put("fieldName", fieldName);
					model.put("filePath", ext+"/"+strName);
					return new ModelAndView("pages/common/uploadsuccess", model);
				}catch(Exception e){
					logger.equals(e);
					throw new BusinessException("上传文件失败："+e.getMessage());
				}
				finally{
					//必须在finally中关闭输入/输出流
					if(input!=null)
						input.close();
					if(output!=null)
						output.close();
				}
			}
		}else{
			//非multipart/form-data请求，发生一个错误
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
		return null;
	}

}
